/*
 * Copyright 2009 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.splink.deepsplink.boot {
	import org.splink.deepsplink.config.ConfigDataReader;
	import org.splink.library.distributor.Distributor;
	import org.splink.library.loading.QUrlLoader;
	import org.splink.library.queue.IQable;
	import org.splink.library.queue.QEvent;

	import flash.net.URLRequest;
	import flash.utils.getQualifiedClassName;

	/**
	 * Bootstrapper for the deepsplink framework, which uses an external configuration file.
	 * It loads the configuration, creates the configuration data model and initializes the 
	 * framework by invoking <code>Bootstrapper</code> with the given 
	 * <code>IDeepsplinkBootstrapStrategy</code>.
	 * 
	 * @author Max Kugland
	 */
	final public class ExternalConfigBootstrapper extends Distributor implements IQable {
		private var _configUrl : String;
		private var _strategy : IBootStrategy;
		private var _loader : QUrlLoader;

		public function ExternalConfigBootstrapper(configUrl : String, strategy : IBootStrategy) {
			_configUrl = configUrl;
			_strategy = strategy;
		}

		/**
		 * @inheritDoc
		 */
		public function get id() : String {
			return getQualifiedClassName(ExternalConfigBootstrapper);
		}

		/**
		 * @inheritDoc
		 */
		public function start() : void {
			_loader = new QUrlLoader(new URLRequest(_configUrl));
			_loader.register(QEvent.COMPLETE, onConfig);			_loader.register(QEvent.PROGRESS, onProgress);			_loader.register(QEvent.ERROR, onError);
			_loader.start();
		}

		private function onProgress(e : QEvent) : void {
			distribute(e.clone(this));
		}

		/**
		 * @inheritDoc
		 */
		public function stop() : void {
			_loader.stop();
		}
		
		/**
		 * @inheritDoc
		 */
		public function reset() : void {
			_loader.reset();
		}

		private function onError(e : QEvent) : void {
			distribute(e.clone(this));
			e.source.finalize();
		}
		
		private function onConfig(e : QEvent) : void {
			var reader : ConfigDataReader = new ConfigDataReader(XML(QUrlLoader(e.source).getContent()));
			new Bootstrapper(reader.read(), _strategy);			distribute(new QEvent(this, QEvent.COMPLETE, id));
		}
		
		/**
		 * @inheritDoc
		 */
		override public function finalize() : void {
			super.finalize();
			if(_loader) {
				_loader.finalize();
				_loader = null;
			}
			_strategy = null;
		}
	}
}
